package com.wnnight.wys.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnnight.wys.entity.role.MenuPerm;
import com.wnnight.wys.mapper.role.MenuPermMapper;
import com.wnnight.wys.security.JwtUtils;
import com.wnnight.wys.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Slf4j
public class AuthFilter implements Filter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private MenuPermMapper menuPermMapper;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;

        String uri = req.getRequestURI();
        if (uri.equals("/login") || uri.equals("/menu/getusermenus")) {
            filterChain.doFilter(req, servletResponse);
            return;
        }
        String jwt = req.getHeader("jwt");
        int roleId = (int) jwtUtils.getInfo(jwt, "roleId");
        log.debug("uri:{}",uri);
        log.debug("roleId:{}",roleId);
        List<MenuPerm> userPermissions = menuPermMapper.getByRoleId(roleId);
        for (MenuPerm userPerm : userPermissions) {
            if (uri.equals(userPerm.getUrl())) {
                filterChain.doFilter(req, servletResponse);
                return;
            }
        }
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(new ResultVo<>(700,"NOPERM","权限不足"));
        servletResponse.setContentType("application/json");
        servletResponse.getWriter().print(json);
        servletResponse.getWriter().close();
    }
}
